import { Toast } from "vant";
import { app } from "../store/AppStore";

function isAssignFalse(val) {
  return val !== undefined && val !== null && !val;
}

/**
 * @param {VueRouter} router
 */
export const registerAuthGuard = router => {
  router.beforeEach(async (to, from, next) => {
    if (isAssignFalse(to.meta?.auth)) {
      next();
      return;
    }

    if (!app.auth) {
      console.log(`AuthGuard login`);
      try {
        Toast.loading();
        await app.reLogin();
      } catch (e) {
        console.log(`AuthGuard login failed`);
        next({ name: "Login" });
        return;
      } finally {
        Toast.clear();
      }
    }

    next();
  });
};
